/*
 * Copyright (c) 2023-2024 elsfs Authors. All Rights Reserved.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package org.elsfs.cloud.common.core.aop;

import java.lang.annotation.Annotation;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
import org.springframework.aop.ClassFilter;
import org.springframework.aop.MethodMatcher;
import org.springframework.aop.Pointcut;
import org.springframework.aop.support.AopUtils;
import org.springframework.aop.support.StaticMethodMatcher;
import org.springframework.core.annotation.AnnotatedElementUtils;
import org.springframework.util.Assert;

/**
 * 注解方法切点
 *
 * @author zeng
 */
public class AnnotationMethodPoint implements Pointcut {
  private final Class<? extends Annotation> annotationType;

  /**
   * 构造方法
   *
   * @param annotationType 注解类型
   */
  public AnnotationMethodPoint(Class<? extends Annotation> annotationType) {
    Assert.notNull(annotationType, "Annotation type must not be null");
    this.annotationType = annotationType;
  }

  @Override
  public ClassFilter getClassFilter() {
    return new AnnotationClassOrMethodFilter(annotationType);
  }

  @Override
  public MethodMatcher getMethodMatcher() {
    return new AnnotationMethodMatcher(this.annotationType);
  }

  private static class AnnotationMethodMatcher extends StaticMethodMatcher {
    private final Class<? extends Annotation> annotationType;

    public AnnotationMethodMatcher(Class<? extends Annotation> annotationType) {
      this.annotationType = annotationType;
    }

    @Override
    public boolean matches(Method method, Class<?> targetClass) {
      if (this.matchesMethod(method)) {
        return true;
      } else if (Proxy.isProxyClass(targetClass)) {
        return false;
      } else {
        Method specificMethod = AopUtils.getMostSpecificMethod(method, targetClass);
        return specificMethod != method && this.matchesMethod(specificMethod);
      }
    }

    private boolean matchesMethod(Method method) {
      return AnnotatedElementUtils.hasAnnotation(method, this.annotationType);
    }
  }
}
